package bussiness.filer;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class PermissionFiler
 */
public class PermissionFiler implements Filter {

    /**
     * Default constructor. 
     */
    public PermissionFiler() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		String username = (String)session.getAttribute("username");
		if(username == null) {			
			if("POST".equals(req.getMethod().toUpperCase())) {
				resp.sendRedirect("/gameforum/login");
			}
			else {
				Map params = req.getParameterMap();
				String next_url = req.getRequestURI();
				String params_str = "";
				Set<String> keys = params.keySet();
				Iterator<String> it = keys.iterator();
				while(it.hasNext()){
					String name = it.next();
					params_str += name + "=" + ((String[])params.get(name))[0] + "&";
				}
				if(params_str.length() > 0)
					params_str = params_str.substring(0, params_str.length()-1);
				String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() ;
				next_url = basePath + next_url + "?" + params_str;
				String encode_url = URLEncoder.encode(next_url, "UTF-8");
				resp.sendRedirect("/gameforum/login?next_url=" + encode_url);
			}
			return;
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
